//
//  SearchSubjectViewController.m
//  History
//
//  Created by jam on 16/9/5.
//  Copyright © 2016年 kane. All rights reserved.
//

#import "SearchSubjectViewController.h"
#import "ChannelAddViewController.h"
#import "NewsListController.h"

@interface SearchSubjectViewController ()<UISearchBarDelegate,UITableViewDelegate,UITableViewDataSource>
{
    __weak IBOutlet UIScrollView *scrollView;
    __weak IBOutlet UISearchBar *searchBar;
    __weak IBOutlet UIView *recommendView;
    __weak IBOutlet UITableView *searchResultTable;
    __weak IBOutlet UILabel *tipLab;
    __weak IBOutlet UIView *searchBgView;
    NSMutableArray *resultDataList;
    NSMutableArray *tipDataList;
}


@end

@implementation SearchSubjectViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    resultDataList = [NSMutableArray array];
    tipDataList = [NSMutableArray array];
    searchResultTable.hidden = YES;
    scrollView.contentSize = CGSizeMake(self.view.width, 500);
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeNightMode) name:kChangeNightMode object:nil];
    [self initTipUI];
    [self changeNightMode];
}

-(void)initTipUI
{
    searchBgView.layer.cornerRadius = 15;
    searchBar.layer.cornerRadius = 15;
    searchBar.layer.masksToBounds = YES;
    for (UIView *subView in searchBar.subviews) {
        for (UIView *sub in subView.subviews) {
            if (![sub isKindOfClass:NSClassFromString(@"UISearchBarTextField")]) {
                [sub removeFromSuperview];
            }
        }
    }
    NSDictionary *params = @{@"channel_status":@"2"};
    [WebService findChannelList:params WithBlock:^(id result, NSError *error) {
        if (!error) {
            if ([result[@"errcode"] integerValue] == 0) {
                NSArray *dataAry = result[@"result"][@"channel"][@"value"];
                [tipDataList removeAllObjects];
                [tipDataList addObjectsFromArray:dataAry];
                [self setupTipListWithTipAry:tipDataList];
                [searchResultTable reloadData];
            }
        }
    }];
}

-(void)setupTipListWithTipAry:(NSArray *)ary
{
    NSInteger count = ary.count> 8 ? 8: ary.count;
    for (int i = 0; i < count; i++) {
        UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(15+145*(i%2), 45+(i/2)*40, 140, 35)];
        bgView.backgroundColor = KKColor_DarkGray_White;
        bgView.layer.cornerRadius = 5;
        bgView.tag = CellOffset+i;
        [recommendView addSubview:bgView];
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
        btn.frame = CGRectMake(45, 5, 60, 30);
        btn.tag = CellOffset*2+i;
        NSDictionary *dict = ary[i];
        NSString *name = dict[@"channel_name"];
        [btn setTitle:name forState:UIControlStateNormal];
        [btn setTitleColor:KKColor_White_Black forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(tipBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [bgView addSubview:btn];
    }
    scrollView.contentSize = CGSizeMake(self.view.width, 1000);
}

-(void)changeNightMode
{
    self.view.backgroundColor = KKcolor_White_SearchBlack;
    for (int i =0; i < tipDataList.count; i++) {
        UIView *sub = [self.view viewWithTag:CellOffset+i];
        sub.backgroundColor = KKcolor_White_SearchViewBlack;
        UIButton *bt = (UIButton *)[self.view viewWithTag:CellOffset*2+i];
        [bt setTitleColor:KKColor_White_Black forState:UIControlStateNormal];
    }
}

-(void)reloadSearchDataList
{
    NSDictionary *params = @{@"channel_name":searchBar.text};
    [WebService getChanelListByName:params WithBlock:^(id result, NSError *error) {
        if (!error) {
            if ([result[@"errcode"] integerValue] == 0) {
                NSArray *dataAry = result[@"result"][@"channel"][@"value"];
                [resultDataList removeAllObjects];
                [resultDataList addObjectsFromArray:dataAry];
                [searchResultTable reloadData];
            }
        }
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark --scrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [searchBar resignFirstResponder];
}

#pragma mark --SearchBarDelegate

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if (searchText.length >0) {
        [self reloadSearchDataList];
        searchResultTable.hidden = NO;
    }
    if (searchText.length ==0) {
        [resultDataList removeAllObjects];
        searchResultTable.hidden = YES;
    }
}

#pragma mark tableviewdelegata

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return resultDataList.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
    }
    NSDictionary *item = resultDataList[indexPath.row];
    if ([item[@"channel_icon"] convertToString].length > 0) {
        [cell.imageView setImageWithURL:[NSURL URLWithString:[FileURL stringByAppendingString:item[@"channel_icon"]]] placeholderImage:[UIImage imageNamed:@"defaultImage"]];
    }
    cell.textLabel.text = [NSString stringWithFormat:@"%@",[item[@"channel_name"] convertToString]];
    cell.detailTextLabel.text = [NSString stringWithFormat:@"%@万人订阅",[item[@"channel_subscriptioncount"] convertToString]];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary *item = resultDataList[indexPath.row];
    if ([item[@"is_sub"] convertToString].length ==0) {
        ChannelAddViewController *channelAddVC = [[ChannelAddViewController alloc] init];
        channelAddVC.dataInfo = item;
        [self.navigationController pushViewController:channelAddVC animated:YES];
    }else {
        NewsListController *newsVC = [[NewsListController alloc] init];
        newsVC.dataInfo = item;
        [self.navigationController pushViewController:newsVC animated:YES];
    }
}

- (void)tipBtnClick:(UIButton *)sender
{
    NSInteger num = sender.tag -CellOffset*2;
    NSDictionary *item = tipDataList[num];
    if ([item[@"is_sub"] convertToString].length ==0) {
        ChannelAddViewController *channelAddVC = [[ChannelAddViewController alloc] init];
        channelAddVC.dataInfo = item;
        [self.navigationController pushViewController:channelAddVC animated:YES];
    }else {
        NewsListController *newsVC = [[NewsListController alloc] init];
        newsVC.dataInfo = item;
        [self.navigationController pushViewController:newsVC animated:YES];
    }
}

- (IBAction)cancelBtnClick:(UIButton *)sender {
    
    [self.navigationController popViewControllerAnimated:NO];
}


@end
